#!/bin/bash

PATH="$PATH:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/usr/local/mysql/bin:/root/bin"

password=0816713
mysql_exec="/usr/local/mysql/bin/mysqldump"

# get the current path of the shell file
basepath=$(cd `dirname $0`; pwd)

# The log file
DATE=$(date +%Y%m%d)
OUTFILE=$basepath/stats$DATE.log

bakdir="$basepath/dbbak"
if [ ! -d "$bakdir" ] ; then
    mkdir "$bakdir"
fi

db=dami_user_data

curr_date=$(date +%Y%m%d)

old_date=$(date -d"-3day" +%Y%m%d)

# Backup to the dir
$mysql_exec -uroot -p"$password" "$db"  | gzip > "$bakdir/""$db""$curr_date".sql.gz

# check if the file is exists
if [ ! -f "$bakdir/""$db""$curr_date".sql.gz ] ; then
	 message=$(date "+%Y-%m-%d %H:%M:%S")"  Can not back the $db to ""$bakdir/""$db""$curr_date".sql.gz
	 echo $message >> $OUTFILE
	 exit
else
   message=$(date "+%Y-%m-%d %H:%M:%S")"  Success back the $db to ""$bakdir/""$db""$curr_date".sql.gz
	 echo $message >> $OUTFILE
fi

# Delete the old bakdatabase files
rm -rf "$bakdir/""$db""$old_date".sql.gz
if [ ! -f "$bakdir/""$db""$old_date".sql.gz ] ; then
	 message=$(date "+%Y-%m-%d %H:%M:%S")" Success remove the $db backfile ""$bakdir/""$db""$old_date".sql.gz
   echo $message >> $OUTFILE
else
	 message=$(date "+%Y-%m-%d %H:%M:%S")" failed remove the $db backfile ""$bakdir/""$db""$old_date".sql.gz
   echo $message >> $OUTFILE
fi

for i in {0..9}
do
	#  Backup to the dir
    db=dami_stat_data_${i}
    $mysql_exec -uroot -p"$password" "$db"  | gzip > "$bakdir/""$db""$curr_date".sql.gz
    if [ ! -f "$bakdir/""$db""$curr_date".sql.gz ] ; then
    	  message=$(date "+%Y-%m-%d %H:%M:%S")"  Can not back the $db to ""$bakdir/""$db""$curr_date".sql.gz
	      echo $message >> $OUTFILE
		    exit
		else
		    message=$(date "+%Y-%m-%d %H:%M:%S")" Success back the $db to ""$bakdir/""$db""$curr_date".sql.gz
	      echo $message >> $OUTFILE
    fi
    
    # delete the old sqlback files.
    rm -rf "$bakdir/""$db""$old_date".sql.gz
    if [ ! -f "$bakdir/""$db""$old_date".sql.gz ] ; then
    	 message=$(date "+%Y-%m-%d %H:%M:%S")" Success remove the $db backfile ""$bakdir/""$db""$old_date".sql.gz
	     echo $message >> $OUTFILE
	  else
	  	 message=$(date "+%Y-%m-%d %H:%M:%S")" failed remove the $db backfile ""$bakdir/""$db""$old_date".sql.gz
	     echo $message >> $OUTFILE
    fi
    
done

